package com.czy.entity;

import com.google.zxing.EncodeHintType;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.Data;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 二维码 条形码 配置类
 * @author czy
 * @date 2021-12-6 15:38
 */
@Data
public class CodeParams {
    private String text;                //内容
    private String codeFormat = "jpg"; //保存格式
    private String barCodeWords;            // 条形码下方文字
    private Image logoImage;               // 二维码logo图片
    private Integer width = 300;           //宽度
    private Integer height = 300;          //高度
    private Integer onColor = 0xFF000000;  //前景色
    private Integer offColor = 0xFFFFFFFF; //背景色
    private Integer margin = 1;            //白边大小，取值范围0~4
    private String charset = "utf-8";
    //二维码容错率 L = ~7% /M = ~15% /Q = ~25% /H = ~30% 容错率越高,二维码的有效像素点就越多
    private ErrorCorrectionLevel level = ErrorCorrectionLevel.M;
    /** 二维码中的Logo缩放的比例系数，如5表示长宽最小值的1/5 */
    protected int ratio = 6;

    public CodeParams() {}

    /**
     * 构造
     *
     * @param width 宽
     * @param height 长
     */
    public CodeParams(int width, int height) {
        this.width = width;
        this.height = height;
    }

    /**
     * 设置二维码logo图片
     * @param path logo图片路径
     */
    public void setLogoImage(String path){
        setLogoImage(new File(path));
    }

    /**
     * 设置二维码logo图片
     * @param file logo图片文件
     */
    public void setLogoImage(File file){
        try {
            this.logoImage = ImageIO.read(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 用于设置QR二维码参数
     * @return
     */
    public Map<EncodeHintType, Object> toHints() {
        Map<EncodeHintType, Object> hints = new HashMap<>();
        // 设置QR二维码的纠错级别（H为最高级别）具体级别信息
        hints.put(EncodeHintType.ERROR_CORRECTION, this.level);
        // 设置边距，既二维码和背景之间的边距
        hints.put(EncodeHintType.MARGIN, this.margin);
        // 设置编码方式
        hints.put(EncodeHintType.CHARACTER_SET, this.charset);
        return hints;
    }
}
